package me.aartikov.alligator.helpers;


import me.aartikov.alligator.animations.DialogAnimation;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;

import java.util.Optional;

/**
 * Helper class for showing and hiding a dialog fragment.
 */
public class DialogFractionHelper {
    private static final String TAG = "me.aartikov.alligator.DIALOG_FRAGMENT_HELPER_TAG";
    private FractionManager mFragmentManager;

    public DialogFractionHelper(FractionManager fragmentManager) {
        mFragmentManager = fragmentManager;
    }


    public DialogFraction getDialogFragment() {
        try {
            Optional<Fraction> optional = mFragmentManager.getFractionByTag(TAG);

            if (optional.isPresent()) {
                if (optional.get() instanceof DialogFraction) {
                    return (DialogFraction) optional.get();
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    public boolean isDialogVisible() {
        return getDialogFragment() != null;
    }

    public void showDialog(DialogFraction dialogFragment, DialogAnimation animation) {
        animation.applyBeforeShowing(dialogFragment);
        dialogFragment.show(mFragmentManager);
        mFragmentManager.startFractionScheduler().submit();
        animation.applyAfterShowing(dialogFragment);
    }

    public void hideDialog() {
        DialogFraction dialogFragment = (DialogFraction) mFragmentManager.getFractionByTag(TAG).get();
        if (dialogFragment == null) {
            throw new IllegalStateException("Dialog is not visible.");
        }
        dialogFragment.dismiss();
//		mFragmentManager.executePendingTransactions();
        mFragmentManager.startFractionScheduler().submit();
    }
}
